const http = require("http");

// const createHandler = require("github-webhook-handler");//这是 对应github的
const createHandler = require("gitee-webhook-middleware"); //码云的需要使用
let handler = createHandler({
    path: "/webhook",
    token: "myToken",
});

function run_cmd(cmd, args, callback) {
    let spawn = require("child_process").spawn;
    let child = spawn(cmd, args);

    let resp = "";
    child.stdout.on("data", function(buffer) {
        resp += buffer.toString();
    });
    child.stdout.on("end", function() {
        callback(resp);
    });
}

let server = http.createServer((req, res) => {
    handler(req, res, function(err) {
        res.statusCode = 404;
        res.end("有点小问题");
    });
});

server.listen(7777, function() {
    console.log("webHooks listen at 7777");
});

handler.on("Push Hook", function(event) {
    console.log("received a push event");
    // console.log("name:", event.payload.repository.name);
    // console.log("ref:", event.payload.ref);

    // 分支判断
    if (event.payload.ref == "refs/heads/master") {
        console.log("主分支 master1");
        run_cmd("sh", ["./deploy.sh"], function(text) {
            console.log("部署结果：", text);
        });
    }
});

handler.on("*", function(event) {
    console.log("全部接受：", event.event);
    // console.log(event.payload);
    // console.log(event.protocol);
    // console.log(event.host);
    // console.log(event.url);
});

handler.on("error", function(error) {
    console.log("Error:", error.message);
});